package com.qf.dao.Impl;

import com.qf.dao.CartDao;
import com.qf.domain.Cart;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public Cart findByUidAndGid(int uid, int pid) {
        String sql = " select id,pid,Num,money from tb_cart where id = ? and pid=? ";
        try {
            Cart query = queryRunner.query(sql, new BeanHandler<>(Cart.class), uid, pid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insert(Cart cart) {
        String sql = " INSERT INTO `tb_cart` (`id`, `pid`, `Num`, `money`) VALUES (?, ?, ?, ?) ";
        try {
            queryRunner.update(sql,cart.getId(), cart.getPid(), cart.getNum(), cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("新增失败");
        }
    }

    @Override
    public void updateCart(Cart cart) {
        String sql = " UPDATE `tb_cart` SET `Num`=?, `money`=? WHERE (`id`=?) AND (`pid`=?) ";
        try {
            queryRunner.update(sql,cart.getNum(), cart.getMoney(), cart.getId(), cart.getPid());
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新失败!!");
        }
    }

    @Override
    public List<Cart> findByUid(int Uid) {
        String sql = " select id ,pid ,num , money from tb_cart where id = ? ";
        try {
            List<Cart> query = queryRunner.query(sql, new BeanListHandler<>(Cart.class), Uid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询购物车失败!!");
        }
        return null;
    }

    @Override
    public void deleteCCart(int id, int pid) {
        String sql = " delete from tb_cart where id = ? and pid = ? ";
        try {
            queryRunner.update(sql,id,pid);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("删除失败!!!");
        }
    }

    @Override
    public void clearCart(int uid) {
        Connection conn = DataSourceUtil.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "delete from tb_cart where id = ? ";
        try {
            queryRunner.update(conn,sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("清空购物车失败!!");
        }
    }
}
